#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    int pipefd[2];
    pid_t pid;
    char buf[1024];

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (pid == 0) { 
        close(pipefd[1]); 
        while (1) {
			memset(buf,0,strlen(buf));
            ssize_t n = read(pipefd[0], buf, sizeof(buf));
            if (n <= 0||(strncmp(buf,"quit",4)==0)) {
                printf("fork 退出！\n");
				break;
            }
			putchar('\n');
            printf("子进程接收到： %s\n", buf);
        }
        close(pipefd[0]);
        exit(EXIT_SUCCESS);
    } else { 
        close(pipefd[0]); 
        while (1) {
			memset(buf,0,strlen(buf));
            printf("请输入要发送的数据（输入 'quit' 退出）：");
			fgets(buf, sizeof(buf), stdin);
			buf[strlen(buf)-1]='\0';
            write(pipefd[1], buf, strlen(buf));
            if (strncmp(buf, "quit", 4) == 0) {
                close(pipefd[1]);
                break;
            }
        }
        wait(NULL); 
    }
    return 0;
}

